package com.ideal.gpt.app.local;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.lzwork.utility.TimeTicker;
import com.lzwork.utility.counter.ItemCounter;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.file.LineContent;
import com.lzwork.utility.officeparser.ExcelLoader;
import com.lzwork.utility.officeparser.ExcelReader;
import com.lzwork.utility.officeparser.ExcelReader.Line;
import com.lzwork.utility.officeparser.ExcelSaver;
import com.lzwork.utility.pair.StringPair;
import com.lzwork.utility.str.StrUtility;

/**
 * @author LiZheng
 * @date 2023年11月27日 下午3:46:18
 */

public class SynchTitle extends ExcelSaver
{
	static char[] repWords =
	{ '?', '"', '<', '>', '*', ':' };
	static String[] delWords =
	{ "/" };

	static String[] suffixCut =
	{ "  (2)", "  (3)", "  (4)" };

	public static File getMapperFile(File target)
	{
		return FileUtility.getFileSafe(target.getParent(), target.getName() + ".titlemap.txt");
	}

	public static void doSynch(File input, File index, File output, boolean refresh)
	{
		Map<String, String> titleKeyMap = new HashMap<>();
		Map<String, String> rawTitleMap = new HashMap<>();
		TimeTicker ticker = new TimeTicker();

		System.out.println("Loading index file.");

		ItemCounter<String> renamer = new ItemCounter<>();

		for (Line line : ExcelReader.read(index).allLineIterator())
		{
			String id = line.getFieldData("KL_ID");
			String rawTitle = line.getFieldData("KL_CONTENT_TITLE");
			String title = rawTitle;

			if (StrUtility.stringValid(true, id, title))
			{
				title = title.trim();
				if (title.length() > 50)
					title = title.substring(0, 50);

				for (char c : repWords)
				{
					title = title.replace(c, '_');
				}
				for (String s : delWords)
				{
					title = title.replace(s, "");
				}

				if (titleKeyMap.containsKey(title))
				{
					Integer num = renamer.getCountNum(title, null);

					if (num == null)
					{
						num = 2;
						renamer.addItem(title, 2);
					}

					String fileTitle = title;
					title += " (" + num + ")";
					System.out.println("Rename duplicated title: " + fileTitle + " to " + title);
					renamer.addItem(fileTitle);
				}
				titleKeyMap.put(title, id);
				if (!title.equals(rawTitle))
					rawTitleMap.put(title, rawTitle);
			}
		}
		File titlemap = getMapperFile(output);
		LineContent.saveFile(titlemap, rawTitleMap, "/");

		System.out.println("Loading index file done. Cost " + ticker.tickS());

		System.out.println("Loading data file.");
		Workbook wb = ExcelLoader.loadWorkBook(input);
		System.out.println("Loading data file done. Cost " + ticker.tickS());

		int pick = 0;

		List<String> missing = new ArrayList<>();

		loopsheet: for (Sheet sheet : wb)
		{
			if (!sheet.getSheetName().startsWith("Q"))
				continue loopsheet;

			StringPair lastId = null;

			lineloop: for (Row row : sheet)
			{
				if (row.getRowNum() == 0)
					continue lineloop;

				String id = null;

				if (!refresh)
				{
					id = ExcelLoader.getCellData(row.getCell(idCol)).getString();
					if (StrUtility.stringValid(id))
						continue lineloop;
				}

				String title = ExcelLoader.getCellData(row.getCell(titleCol)).getString();

				if (!StrUtility.stringValid(title))
				{
					if (lastId == null)
						continue lineloop;
					id = lastId.second();
					title = lastId.first();
				} else
				{
					lastId = null;

					title = title.replace(".txt", "").trim();

					if (title.endsWith("0000644"))
						title = title.replace("0000644", "");

					id = titleKeyMap.get(title);

					if (StrUtility.stringValid(id))
					{
						lastId = new StringPair(title, id);
						pick++;
					} else
					{
						if (title.endsWith(")"))
						{
							for (String s : suffixCut)
							{
								if (title.endsWith(s))
								{
									title = title.replace(s, "");
									id = titleKeyMap.get(title);
									if (StrUtility.stringValid(id))
										break;
								}
							}
						}

						while (title.endsWith("_"))
						{
							title = title.substring(0, title.length() - 1);
							id = titleKeyMap.get(title);

							if (StrUtility.stringValid(id))
							{
								break;
							}
						}

						if (StrUtility.stringValid(id))
						{
							lastId = new StringPair(title, id);
							pick++;
						} else
							missing.add(title);
					}
				}

				if (StrUtility.stringValid(id))
				{
					Cell idCell = pickCellAt(row, idCol);
					idCell.setCellValue(id);

					Cell titleCell = pickCellAt(row, titleCol);
					titleCell.setCellValue(title);
				}
			}
		}

		if (missing.size() > 0)
			System.out.println("Missing:\n\t" + StrUtility.combineString(missing, "\n\t"));

		System.out.println(pick + " ids picked. Missing " + missing.size());
		saveXlsFile(wb, output);
	}

	static int titleCol = 1;
	static int idCol = 0;

	public static void main(String[] args)
	{
		File folder = new File("V:/12345/input_txt_raw/");

		File input = FileUtility.getFileSafe(folder, "全量政策文件出题_2000_1.xlsx");
		File index = FileUtility.getFileSafe(folder, "KL_CONTENT_INFO_INDEX.xlsx");
		File output = FileUtility.getFileSafe(folder, "全量政策文件出题_2000_Full.xlsx");

		doSynch(input, index, output, true);
	}
}
